package com.erp.order.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.order.mapper.ErpSellerOrderMapper;
import com.erp.order.service.IAeOrderService;
import com.erp.order.service.IAeSaveOrderService;
import com.ruoyi.ae.api.RemoteAeOrderService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.ruoyi.order.api.domain.ErpSellerOrderExtend;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@RequiredArgsConstructor
@Service
public class AeOrderServiceImpl implements IAeOrderService {

    @Resource
    private RemoteSellerStoreService remoteSellerStoreService;
    private final RemoteAeOrderService remoteAeOrderService;
    //    @Autowired
//    ISysConfigService configService;
//    @Autowired
//    IErpSellerStoreEmpowerService iErpSellerStoreEmpowerService;
//    @Autowired
//    IErpSellerOrderService iErpSellerOrderService;
    private final ErpSellerOrderMapper erpSellerOrderMapper;
    private final IAeSaveOrderService iAeSaveOrderService;
//    private final ErpCollectProductSkuMapper erpCollectProductSkuMapper;
//    private final IErpSellerOrderLogService orderLogService;
//    private final IErpSellerStoreEmpowerService erpSellerStoreEmpowerService;
//    private final ErpCollectAbsentSkuMapper erpCollectAbsentSkuMapper;
//    private final ErpSellerOrderProductMapper erpSellerOrderProductMapper;
//    private final ErpSellerOrderExtendMapper erpSellerOrderExtendMapper;
//    private final IErpOrderProductStatisticsService iErpOrderProductStatisticsService;
//    private final IErpOrderInfoStatisticsService orderInfoStatisticsService;
//    private final ErpSellerChildOrderMapper erpSellerChildOrderMapper;
//    private final ErpSellerStoreEmpowerMapper erpSellerStoreEmpowerMapper;
//
//    private final AEConfig aeConfig;
//    private final ErpSellerStoreProductEvaluationMapper erpSellerStoreProductEvaluationMapper;
//    private final AeStoreOrderReceiptAddressMapper addressMapper;
//    private final ErpSellerStoreEmpowerMapper empowerMapper;
//    private final IErpInternetCelebrityStatisticService iErpInternetCelebrityStatisticService;

//    /**
//     * 保存订单
//     *
//     * @param orderList
//     * @return
//     */
//    @Override
//    @Transactional
//    public R<String> saveList(List<ErpSellerOrder> orderList) {
//        for (ErpSellerOrder order : orderList) {
//            //判断数据库中是否已存在该订单号
//            ErpSellerOrder erpSellerOrderSel = erpSellerOrderMapper.queryOrderByOrderId(order.getOrderId());
//            //现在系统中已有订单的状态
//            String selOrderStatus = null;
//            if (erpSellerOrderSel != null) {
//                order.setId(erpSellerOrderSel.getId());
//                selOrderStatus = erpSellerOrderSel.getOrderStatus();
//            }
//            String orderStatus = order.getOrderStatus();
//            if (!orderStatus.equals(selOrderStatus)) {
//                //改变状态
//                //Erp内部状态
////                String nowErpStatus = order.getErpInnerOrderStatus();
//                String newErpStatus = null;
//                String orderError = "已获取到订单";
//                //根据订单状态，分配不同的状态
//                if (orderStatus.equals("PLACE_ORDER_SUCCESS")) {
//                    //PLACE_ORDER_SUCCESS:等待买家付款 未付款
//                    newErpStatus = "100";
//                } else if (orderStatus.equals("WAIT_SELLER_SEND_GOODS")) {
//                    //WAIT_SELLER_SEND_GOODS:等待您发货 102
//                    newErpStatus = "101";
//                } else if (orderStatus.equals("SELLER_PART_SEND_GOODS")) {
//                    //部分发货; （待发货）
//                    newErpStatus = "102";
//                } else if (orderStatus.equals("WAIT_BUYER_ACCEPT_GOODS")) {
//                    //等待买家收货; （已发货）
//                    newErpStatus = "107";
//                } else if (orderStatus.equals("IN_CANCEL")) {
//                    //买家申请取消 问题件 701
//                    newErpStatus = "701";
//                    orderError = "买家申请取消";
//                } else if (orderStatus.equals("FUND_PROCESSING")) {
//                    //买卖家达成一致，资金处理中； （问题单）
//                    newErpStatus = "701";
//                    orderError = "买卖家达成一致，资金处理中";
//                } else if (orderStatus.equals("IN_ISSUE")) {
//                    //含纠纷中的订单;  （问题单）
//                    newErpStatus = "701";
//                    orderError = "含纠纷中的订单";
//                } else if (orderStatus.equals("IN_FROZEN")) {
//                    //冻结中的订单;  （问题单）
//                    newErpStatus = "701";
//                    orderError = "订单冻结中";
//                } else if (orderStatus.equals("WAIT_SELLER_EXAMINE_MONEY")) {
//                    //等待您确认金额; （问题单）
//                    newErpStatus = "701";
//                    orderError = "等待您确认金额";
//                } else if (orderStatus.equals("RISK_CONTROL")) {
//                    //订单处于风控24小时中，从买家在线支付完成后开始，持续24小时
//                    newErpStatus = "701";
//                    orderError = "订单处于风控24小时中，从买家在线支付完成后开始，持续24小时";
//                } else if (orderStatus.equals("FINISH")) {
//                    //订单已完成或关闭
//                    newErpStatus = "114";
//                    orderError = "订单已完成或关闭";
//                } else {
//                    //其他问题 问题件 701
//                    newErpStatus = "701";
//                    orderError = "其他问题";
//                }
//                // 更新日志
//                ErpSellerOrderLogBo orderLog = new ErpSellerOrderLogBo();
//                orderLog.setOrderId(order.getOrderId());
//                orderLog.setStatusIntro(orderError);
//                String storeNameByUserName = erpSellerStoreEmpowerService.getStoreNameByUserName(order.getSellerLoginId());
//                orderLog.setStoreName(storeNameByUserName);
//                orderLog.setErpAccount(erpSellerStoreEmpowerService.queryUserNameBySellerLoginId(order.getSellerLoginId()));
//                orderLogService.insertByBo(orderLog);
//                //更改状态
//                order.setErpInnerOrderStatus(newErpStatus);
//            } else {
//                order.setErpInnerOrderStatus(erpSellerOrderSel.getErpInnerOrderStatus());
//            }
//
//
//            order.setCreateTime(new Date());
//            order.setUpdateTime(new Date());
//            if (order.getSellerChildOrderList() != null && order.getSellerChildOrderList().size() > 0) {
//                ErpCollectProductSku erpCollectProductSku = new ErpCollectProductSku();
//                ErpCollectAbsentSku erpCollectAbsentSku = new ErpCollectAbsentSku();
//
//                for (ErpSellerChildOrder erpSellerChildOrder : order.getSellerChildOrderList()) {
//                    //判断该订单的商品的skucode在数据库中是否存在
//                    erpCollectProductSku = erpCollectProductSkuMapper.selectOne(
//                            new LambdaQueryWrapper<ErpCollectProductSku>()
//                                    .eq(ErpCollectProductSku::getSkuCode, erpSellerChildOrder.getSkuCode())
//                                    .eq(ErpCollectProductSku::getDelFlag, "0")
//                    );
//                    if (erpCollectProductSku == null) {
//                        //查询该商品是否已属于该表
//                        erpCollectAbsentSku = erpCollectAbsentSkuMapper.selectOne(
//                                new LambdaQueryWrapper<ErpCollectAbsentSku>().eq(ErpCollectAbsentSku::getSkuCode, erpSellerChildOrder.getSkuCode())
//                        );
//                        if (erpCollectAbsentSku == null) {
//                            erpCollectAbsentSku = new ErpCollectAbsentSku();
//                            String url = "https://www.aliexpress.us/item/";
//                            //向晓翔表里插入数据
//                            erpCollectAbsentSku.setOrderId(erpSellerChildOrder.getOrderId().toString());
//                            erpCollectAbsentSku.setChildOrderId(erpSellerChildOrder.getChildOrderId());
//                            erpCollectAbsentSku.setSkuCode(erpSellerChildOrder.getSkuCode());
//                            erpCollectAbsentSku.setCollectLink(url + erpSellerChildOrder.getProductId() + ".html");
//                            erpCollectAbsentSku.setStatus("0");
//                            erpCollectAbsentSkuMapper.insert(erpCollectAbsentSku);
//                        }
//                    }
//                    erpSellerChildOrderMapper.insertOrUpdate(BeanUtil.copyProperties(erpSellerChildOrder, ErpSellerChildOrder.class));
//                }
//            }
//            if (order.getSellerOrderProductList().size() > 0) {
//                for (ErpSellerOrderProductVo orderProductvo : order.getSellerOrderProductList()) {
//                    ErpSellerOrderProduct orderProductSel = erpSellerOrderProductMapper.selectOne(
//                            new LambdaQueryWrapper<ErpSellerOrderProduct>()
//                                    .eq(ErpSellerOrderProduct::getSkuCode, orderProductvo.getSkuCode())
//                                    .eq(ErpSellerOrderProduct::getChildId, orderProductvo.getChildId())
//                                    .eq(ErpSellerOrderProduct::getOrderId, orderProductvo.getOrderId())
//                    );
//                    if (orderProductSel != null) {
//                        orderProductvo.setId(orderProductSel.getId());
//                    }
//
//                    erpSellerOrderProductMapper.insertOrUpdate(BeanUtil.copyProperties(orderProductvo, ErpSellerOrderProduct.class));
//                }
//            }
//            //修改订单
//            erpSellerOrderMapper.insertOrUpdate(order);
//
//            //计算预估利润
////            iErpOrderProductStatisticsService.insertProfit(order);
//            orderInfoStatisticsService.saveOrderProfitInfo(order);
//
//            //判断是会否需要后付费
//            iErpSellerOrderService.freezeOrderAmount(order.getOrderId(), 0);
//
//            // 判断是否是网红产品
//            iErpInternetCelebrityStatisticService.judgeProductAndSeller(order.getOrderId());
//            // 判断是否是测评单
////            mateEvaluationOrder(order.getOrderId());
//
//        }
//        return R.ok("获取成功");
//    }
//
//
    // 4.0.0以后合并至pullOrdersFromAliExpress方法统一入口
//    @Override
//    public R<Object> pullOrderFromAe(String sellerId, String createDateStart, String createDateEnd) {
//        List<ErpSellerStoreEmpower> storeEmpowerList = new ArrayList<>();
//        if (Objects.isNull(sellerId)) {
//            R<Object> storeEmpowerObject = remoteSellerStoreService.getEmpowerStore();
//            if(storeEmpowerObject.getCode() != 200){
//                return R.fail("获取店铺授权信息失败");
//            }
//            String storeEmpowerString = JSONObject.toJSONString(storeEmpowerObject.getData());
//            storeEmpowerList = JSONArray.parseArray(storeEmpowerString, ErpSellerStoreEmpower.class);
//        } else {
//            R<Object> storeEmpowerObject = remoteSellerStoreService.getSellerStoreEmpowerByStoreId(sellerId);
//            if(storeEmpowerObject.getCode() != 200){
//                return R.fail("获取店铺授权信息失败");
//            }
//            String storeEmpowerString = JSONObject.toJSONString(storeEmpowerObject.getData());
//            ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(storeEmpowerString, ErpSellerStoreEmpower.class);
//            storeEmpowerList.add(storeEmpower);
//        }
//
//        for (ErpSellerStoreEmpower store : storeEmpowerList) {
//            iAeSaveOrderService.pullOrdersFromAliExpress(store.getId(), createDateStart, createDateEnd);
//        }
//
//        return R.ok();
//
////        List<ErpSellerStoreEmpower> storeEmpowerList = remoteSellerStoreService.getEmpowerStore();
////        for (ErpSellerStoreEmpower store : storeEmpowerList) {
////            iAeSaveOrderService.pullOrdersFromAliExpress(store.getId(), null, null);
////        }
//    }
//
//    @Override
//    public R<Object> findOrderBaseInfo(Long orderId) {
//        ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(orderId);
//        ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectStoreByStoreUserName(order.getSellerLoginId());
//        if (Objects.isNull(store)) {
//            return R.fail("未查找到该店铺");
//        }
//        Map<String, Object> sendMap = new HashMap<>();
//        sendMap.put("orderId", order.getOrderId());
//        sendMap.put("storeId", store.getId());
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpOrder/findOrderBaseInfo", sendMap, String.class);
//        String body = (String) forEntity.getBody();
//        if (!body.contains("aliexpress_trade_redefining_findorderbaseinfo_response")) {
//            return null;
//        }
//        String data = JSONObject.parseObject(body).getString("data");
//        Map<String, Object> returnMap = new HashMap<>();
//        returnMap.put("data", data);
//        returnMap.put("orderId", orderId);
//
//        return R.ok(returnMap);
//    }

    @Override
    public R<Object> findOrderIssueInfo(Long orderId) {
        ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(orderId);
        R<Object> sellerStoreEmpowerByCnCode = remoteSellerStoreService.getSellerStoreEmpowerByCnCode(order.getSellerLoginId());
        ErpSellerStoreEmpower store = JSONObject.parseObject(JSONObject.toJSONString(sellerStoreEmpowerByCnCode.getData()), ErpSellerStoreEmpower.class);
        if (Objects.isNull(store)) {
            return R.fail("未查找到该店铺");
        }
        Map<String, String> sendMap = new HashMap<>();
        sendMap.put("orderId", order.getOrderId().toString());
        sendMap.put("storeId", store.getId().toString());
        R<Object> orderBaseInfo = remoteAeOrderService.findOrderBaseInfo(sendMap);
        String body = JSONObject.toJSONString(orderBaseInfo.getData());
        if (!body.contains("aliexpress_trade_redefining_findorderbaseinfo_response")) {
            return null;
        }

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("data", JSONObject.parseObject(body).getString("data"));
        returnMap.put("orderId", orderId);
        return R.ok(returnMap);
    }

    @Override
    public R<Object> findIssueOrderListByStoreId(String storeId) {
//        if (ObjectUtils.isNotNull(childOrderId)){
//            ErpSellerChildOrder childOrder = erpSellerChildOrderMapper.selectOne(
//                    new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getChildOrderId, childOrderId)
//            );
//            if (childOrder == null) {
//                return R.fail("订单不存在");
//            }
//        }
//
//        ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(childOrder.getOrderId());
//        ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectStoreByStoreUserName(order.getSellerLoginId());
//        sendMap.put("childOrderId", childOrderId);
//        sendMap.put("orderId", order.getOrderId());
        R<Object> object = remoteAeOrderService.findIssueOrderListByStoreId(storeId);
        if (object.getCode() == 200){
            String body = (String) object.getData();
            System.out.println(body);
            JSONArray array = JSONArray.parseArray(body);
            return R.ok(array.size());
        }else {
            return R.ok(0,"暂无纠纷单信息");
        }
    }

//    /**
//     * 更新订单状态
//     */
//    @Override
//    public void updateOrderStatus(String orderStatus) {
//        List<ErpSellerOrder> orderList = erpSellerOrderMapper.selectList(
//                new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getErpInnerOrderStatus, orderStatus)
//        );
//
//        for (ErpSellerOrder order : orderList) {
//            //1、获取该订单
////            ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(orderId);
//
//            //获取订单最新状态
//            ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectStoreByStoreUserName(order.getSellerLoginId());
//            Map<String, Object> sendMap = new HashMap<>();
//            sendMap.put("orderId", order.getOrderId());
//            sendMap.put("storeId", store.getId());
//            ResponseEntity<String> forEntity = restTemplate
//                    .postForEntity(aeConfig.getEndpoint() + "/erp/erpOrder/findOrderBaseInfo", sendMap, String.class);
//            String body = (String) forEntity.getBody();
//            if (!body.contains("aliexpress_trade_redefining_findorderbaseinfo_response")) {
//                continue;
//            }
//            String data = JSONObject.parseObject(body).getString("data");
//            if (body.contains("{}")) {
//                continue;
//            }
//            String newOrderStatus = JSONObject.parseObject(data)
//                    .getJSONObject("aliexpress_trade_redefining_findorderbaseinfo_response")
//                    .getJSONObject("result")
//                    .getString("order_status");
//            String selOrderStatus = order.getOrderStatus();
//            if (!newOrderStatus.equals(selOrderStatus)) {
//                //改变状态
//                //Erp内部状态
////                String nowErpStatus = order.getErpInnerOrderStatus();
//                String newErpStatus = null;
//                String orderError = "已获取到订单";
//                //根据订单状态，分配不同的状态
//                if (newOrderStatus.equals("PLACE_ORDER_SUCCESS")) {
//                    //PLACE_ORDER_SUCCESS:等待买家付款 未付款
//                    newErpStatus = "100";
//                } else if (newOrderStatus.equals("WAIT_SELLER_SEND_GOODS")) {
//                    //WAIT_SELLER_SEND_GOODS:等待您发货 102
//                    newErpStatus = "101";
//                } else if (newOrderStatus.equals("SELLER_PART_SEND_GOODS")) {
//                    //部分发货; （待发货）
//                    newErpStatus = "102";
//                } else if (newOrderStatus.equals("WAIT_BUYER_ACCEPT_GOODS")) {
//                    //等待买家收货; （已发货）
//                    newErpStatus = "107";
//                } else if (newOrderStatus.equals("IN_CANCEL")) {
//                    //买家申请取消 问题件 701
//                    newErpStatus = "701";
//                    orderError = "买家申请取消";
//                } else if (newOrderStatus.equals("FUND_PROCESSING")) {
//                    //买卖家达成一致，资金处理中； （问题单）
//                    newErpStatus = "701";
//                    orderError = "买卖家达成一致，资金处理中";
//                } else if (newOrderStatus.equals("IN_ISSUE")) {
//                    //含纠纷中的订单;  （问题单）
//                    newErpStatus = "701";
//                    orderError = "含纠纷中的订单";
//                } else if (newOrderStatus.equals("IN_FROZEN")) {
//                    //冻结中的订单;  （问题单）
//                    newErpStatus = "701";
//                    orderError = "订单冻结中";
//                } else if (newOrderStatus.equals("WAIT_SELLER_EXAMINE_MONEY")) {
//                    //等待您确认金额; （问题单）
//                    newErpStatus = "701";
//                    orderError = "等待您确认金额";
//                } else if (newOrderStatus.equals("RISK_CONTROL")) {
//                    //订单处于风控24小时中，从买家在线支付完成后开始，持续24小时
//                    newErpStatus = "701";
//                    orderError = "订单处于风控24小时中，从买家在线支付完成后开始，持续24小时";
//                } else if (newOrderStatus.equals("FINISH")) {
//                    //订单已完成或关闭
//                    newErpStatus = "114";
//                    orderError = "订单已完成或关闭";
//                } else {
//                    //其他问题 问题件 701
//                    newErpStatus = "701";
//                    orderError = "其他问题";
//                }
//                // 更新日志
//                if (orderError != null) {
//                    ErpSellerOrderLogBo orderLog = new ErpSellerOrderLogBo();
//                    orderLog.setOrderId(order.getOrderId());
//                    orderLog.setStatusIntro(orderError);
//                    orderLog.setRemark(orderError);
//                    String storeNameByUserName = erpSellerStoreEmpowerService.getStoreNameByUserName(order.getSellerLoginId());
//                    orderLog.setStoreName(storeNameByUserName);
//                    orderLog.setErpAccount(erpSellerStoreEmpowerService.queryUserNameBySellerLoginId(order.getSellerLoginId()));
//                    orderLogService.insertByBo(orderLog);
//                }
//                //更改状态
//                order.setErpInnerOrderStatus(newErpStatus);
//                order.setOrderStatus(newOrderStatus);
//                erpSellerOrderMapper.updateById(order);
//
//                System.out.println("订单" + order.getId() + "状态改为" + newErpStatus);
//            }
//        }
//    }
//
//    @Override
//    public void mateEvaluationOrder(Long orderId) {
//        ErpSellerOrder sellerOrder = erpSellerOrderMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrder>().eq(ErpSellerOrder::getOrderId, orderId));
//        String sellerLoginId = sellerOrder.getSellerLoginId();
//        ErpSellerStoreEmpower storeEmpower = empowerMapper.selectEmpowerByUserName(sellerLoginId);
//        Long storeId = storeEmpower.getId();
//        // 获取订单的skuCode
//        List<ErpSellerChildOrder> childOrderList = erpSellerChildOrderMapper.selectList(new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, orderId));
//        // 测评单只有一个skuCode
//        ErpSellerChildOrder childOrder = childOrderList.get(0);
//        String skuCode = childOrder.getSkuCode();
//        Long productCount = childOrder.getProductCount();
//        // 获取订单的国家
//        AeStoreOrderReceiptAddress address = addressMapper.selectOne(new LambdaQueryWrapper<AeStoreOrderReceiptAddress>().eq(AeStoreOrderReceiptAddress::getOrderId, orderId));
//        if (address == null) {
//            return;
//        }
//        String country = address.getCountry();
//        // 根据店铺,sku,数量,国家匹配测评单
//        LambdaQueryWrapper<ErpSellerStoreProductEvaluation> queryWrapper = new LambdaQueryWrapper<ErpSellerStoreProductEvaluation>()
////                .eq(ErpSellerStoreProductEvaluation::getCountry, country)
//                .eq(ErpSellerStoreProductEvaluation::getSkuCode, skuCode)
//                .eq(ErpSellerStoreProductEvaluation::getStoreId, storeId)
//                .eq(ErpSellerStoreProductEvaluation::getNumber, productCount);
//        List<ErpSellerStoreProductEvaluation> evaluationList = erpSellerStoreProductEvaluationMapper.selectList(queryWrapper);
//        if (evaluationList.size() == 1) { // 有一个匹配的填上订单号 且订单号是空
//            ErpSellerStoreProductEvaluation evaluation = evaluationList.get(0);
//            if (evaluation.getOrderId() == null) {
//                Long evaluationId = evaluation.getId();
//                restTemplate.getForEntity("http://localhost:8860/gather/sellerStoreProductEvaluation/submitOrderNumber?orderNumber=" + orderId + "&evaluationId=" + evaluationId, String.class);
//            }
//        }
//    }
//
//    /**
//     * 获取订单收货地址信息
//     *
//     * @param orderId
//     */
//    @Override
//    public R<Object> findOrderReceiptInfo(Long orderId) {
//        List<ErpSellerOrder> orderList = new ArrayList<>();
//        if (orderId != null) {
//            ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(orderId);
//            orderList.add(order);
//        } else {
//            orderList = erpSellerOrderMapper.selectAddressErrorList();
//        }
//        String body = null;
//        for (ErpSellerOrder orderFor : orderList) {
//            System.out.println(orderFor);
//            Map<String, Object> sendMap = new HashMap<>();
//            sendMap.put("orderId", orderFor.getOrderId());
//            ErpSellerStoreEmpower storeEmpower = erpSellerStoreEmpowerMapper.selectStoreByStoreUserName(orderFor.getSellerLoginId());
//            sendMap.put("storeId", storeEmpower.getId());
//
//            ResponseEntity<String> forEntity = restTemplate
//                    .postForEntity(aeConfig.getEndpoint() + "/erp/erpOrder/findOrderReceiptInfo", sendMap, String.class);
//            body = (String) forEntity.getBody();
//            ErpSellerOrderExtend orderExtend = erpSellerOrderExtendMapper.selectOne(
//                    new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, orderFor.getOrderId())
//            );
//            if (orderExtend == null) {
//                orderExtend = new ErpSellerOrderExtend();
//                orderExtend.setOrderId(orderFor.getOrderId());
//            }
//            if (body.contains("更新成功")) {
//                orderExtend.setType("1");
//            } else {
//                orderExtend.setType("0");
//            }
//            erpSellerOrderExtendMapper.insertOrUpdate(orderExtend);
//        }
//        return R.ok(body);
//    }
//
//    @Override
//    public R<Object> findOrderFeeRateAndCodeInfo(Long orderId) {
//        List<ErpSellerChildOrder> childOrders = new ArrayList<>();
//        if (orderId != null) {
//            childOrders = erpSellerChildOrderMapper.selectList(
//                    new LambdaQueryWrapper<ErpSellerChildOrder>().eq(ErpSellerChildOrder::getOrderId, orderId)
//            );
//        } else {
//            childOrders = erpSellerChildOrderMapper.selectFeeRateAndCodeErrorList();
//        }
//        String body = null;
//        for (ErpSellerChildOrder childOrder : childOrders) {
//            Map<String, Object> sendMap = new HashMap<>();
//            sendMap.put("orderId", childOrder.getOrderId());
//            ErpSellerOrder orderFor = erpSellerOrderMapper.queryOrderByOrderId(childOrder.getOrderId());
//            ErpSellerStoreEmpower storeEmpower = erpSellerStoreEmpowerMapper.selectStoreByStoreUserName(orderFor.getSellerLoginId());
//            sendMap.put("storeId", storeEmpower.getId());
//
//            ResponseEntity<String> forEntity = restTemplate
//                    .postForEntity(aeConfig.getEndpoint() + "/erp/erpOrder/findOrderFeeRateAndCodeInfo", sendMap, String.class);
//            body = (String) forEntity.getBody();
//            String code = JSONObject.parseObject(body).getString("code");
//            if (!code.equals("200")) {
//                continue;
//            }
//            Map<String, Object> map = (Map<String, Object>) JSONObject.parseObject(body).getJSONObject("data");
//            System.out.println(map);
//            for (String key : map.keySet()) {
//                Map<String, Object> childOrderMap = (Map<String, Object>) map.get(key);
//                System.out.println(childOrderMap);
//
//                childOrder.setAfflicateFeeRate((String) childOrderMap.get("afflicateFeeRate"));
//                childOrder.setEscrowFeeRate((String) childOrderMap.get("escrowFeeRate"));
//                childOrder.setProductCurrencyCode((String) childOrderMap.get("productCurrencyCode"));
//
//                erpSellerChildOrderMapper.insertOrUpdate(childOrder);
//            }
//
//        }
//        return R.ok(body);
//    }
//
//    @Override
//    public R<Object> findOrderLeftEndGoodTime() {
//        List<ErpOrderLeftEndGoodTime> orderList = new ArrayList<>();
//        ErpSellerOrder order = new ErpSellerOrder();
//        orderList = erpSellerOrderMapper.findOrderLeftEndGoodTime();
//        for (ErpOrderLeftEndGoodTime orderFor : orderList) {
//            order = erpSellerOrderMapper.queryOrderByOrderId(orderFor.getOrderId());
//            //获取订单详情
//            R<Object> orderMsg = findOrderById(order.getOrderId());
//            Integer code = JSONObject.parseObject(orderMsg.getMsg()).getInteger("code");
//            String msg = JSONObject.parseObject(orderMsg.getMsg()).getString("msg");
//            if (code == 200) {
//                String overTimeLeft =
//                        JSONObject
//                                .parseObject(msg)
//                                .getJSONObject("aliexpress_trade_new_redefining_findorderbyid_response")
//                                .getJSONObject("target")
//                                .getString("over_time_left");
//                System.out.println(order.getOrderId() + ":" + overTimeLeft);
//
//                if (overTimeLeft != null) {
////                    String transition = TimeZoneTransition.transition(overTimeLeft);
////                    System.out.println(order.getOrderId() + ":" + transition);
//                    order.setLeftEndGoodTime(overTimeLeft);
//                    erpSellerOrderMapper.insertOrUpdate(order);
//                }
//            }
//
//        }
//        return R.ok();
//    }
//

//
//    @Override
//    public R<Object> findOrderById(Long orderId) {
//        ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(orderId);
//        if (order == null) {
//            return R.fail("订单不存在");
//        }
//        ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectStoreByStoreUserName(order.getSellerLoginId());
//        Map<String, Object> sendMap = new HashMap<>();
//        sendMap.put("orderId", orderId);
//        sendMap.put("storeId", store.getId());
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/AEOrder/storeOrder/findOrderById", sendMap, String.class);
//        String body = (String) forEntity.getBody();
//
//        return R.ok(body);
//    }
//
//    @Override
//    public R<Object> findOrderFeeRate() {
//        List<ErpSellerOrder> orderList = new ArrayList<>();
//        orderList = erpSellerOrderMapper.findOrderFeeRate();
//        for (ErpSellerOrder order : orderList) {
//            //获取订单详情
//            R<Object> orderMsg = findOrderById(order.getOrderId());
//            Integer code = JSONObject.parseObject(orderMsg.getMsg()).getInteger("code");
//            String msg = JSONObject.parseObject(orderMsg.getMsg()).getString("msg");
//            if (code == 200) {
//                String childOrderList =
//                        JSONObject
//                                .parseObject(msg)
//                                .getJSONObject("aliexpress_trade_new_redefining_findorderbyid_response")
//                                .getJSONObject("target")
//                                .getJSONObject("child_order_list")
//                                .getString("aeop_tp_child_order_dto");
//                JSONArray childOrderArray = JSONArray.parseArray(childOrderList);
//                for (Object childOrder : childOrderArray) {
//                    JSONObject childOrderJson = (JSONObject) childOrder;
//                    Long childOrderId = childOrderJson.getLong("child_order_id");
//                    ErpSellerChildOrder childOrderSel = erpSellerChildOrderMapper.selectOne(
//                            new LambdaQueryWrapper<ErpSellerChildOrder>()
//                                    .eq(ErpSellerChildOrder::getChildOrderId, childOrderId)
//                    );
//                    if (childOrderSel != null) {
//                        childOrderSel.setAfflicateFeeRate(childOrderJson.getString("afflicate_fee_rate"));
//                        childOrderSel.setEscrowFeeRate(childOrderJson.getString("escrow_fee_rate"));
//                        erpSellerChildOrderMapper.updateById(childOrderSel);
//                    }
//                }
//            }
//        }
//        return R.ok();
//    }
//
//    /**
//     * 查找纠纷订单
//     */
//    @Override
//    public void findIssueOrder() {
//        //找到状态为结束的，且状态为114的订单，且订单延伸表中，对应字段为空的
//        List<ErpSellerOrder> erpSellerOrders = erpSellerOrderMapper.findIssueOrder();
//        erpSellerOrders.forEach(
//                order -> {
//                    R<Object> orderBaseInfo = findOrderIssueInfo(order.getOrderId());
//                    if (orderBaseInfo != null && orderBaseInfo.getCode() == 200) {
//                        Map<String, Object> data = (Map<String, Object>) orderBaseInfo.getData();
//                        String dataStr = (String) data.get("data");
//                        JSONObject jsonObject = JSONObject.parseObject(dataStr);
//                        String issueStatus = jsonObject
//                                .getJSONObject("aliexpress_trade_redefining_findorderbaseinfo_response")
//                                .getJSONObject("result")
//                                .getString("issue_status");
//                        if (issueStatus != null && !issueStatus.equals("NO_ISSUE")) {
//                            //有纠纷，创建日志，改变状态
//                            orderLogService.createOrderLog(order.getOrderId(), null, OrderLogType.FindIssueOrder, null, OrderProcessFlag.Issue.getInfo(), "117");
//                            iErpSellerOrderService.updateInnerStatusAndProcess(order.getOrderId(), order.getOrderStatus(), OrderProcessFlag.Issue.getInfo(), "117");
//                        }
//                    }
//                }
//        );
//
//    }
//
//    /**
//     * 获取订单金额（new_order_amount和logistics_amount）
//     */
//    @Override
//    public void updateOrderAmount() {
//        List<ErpSellerOrder> erpSellerOrders = erpSellerOrderMapper.createOrderExtend();
//        erpSellerOrders.forEach(order -> {
//            ErpSellerOrderExtend extend = new ErpSellerOrderExtend();
//            extend.setOrderId(order.getOrderId());
//            erpSellerOrderExtendMapper.insert(extend);
//        });
//
//        List<ErpSellerOrderExtend> erpSellerOrderExtends = erpSellerOrderExtendMapper.selectList(
//                new LambdaQueryWrapper<ErpSellerOrderExtend>()
//                        .isNull(ErpSellerOrderExtend::getLogisticsAmount)
//                        .or()
//                        .isNull(ErpSellerOrderExtend::getNewOrderAmount)
//        );
//
//        for (ErpSellerOrderExtend orderExtend : erpSellerOrderExtends) {
//            Map<String, Object> sendMap = new HashMap<>();
//            if (Objects.isNull(orderExtend)) {
//                continue;
//            }
//            ErpSellerOrder order = erpSellerOrderMapper.queryOrderByOrderId(orderExtend.getOrderId());
//            if (Objects.isNull(order)) {
//                continue;
//            }
//            sendMap.put("orderId", order.getOrderId());
//            ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectStoreByStoreUserName(order.getSellerLoginId());
//            if (Objects.isNull(store)) {
//                continue;
//            }
//            sendMap.put("storeId", store.getId());
//            ResponseEntity<String> forEntity = restTemplate
//                    .postForEntity(aeConfig.getEndpoint() + "/erp/erpOrder/updateOrderAmount", sendMap, String.class);
//            System.out.println(forEntity);
//            String body = forEntity.getBody();
//            String code = JSONObject.parseObject(body).getString("code");
//            if (code.equals("500")) {
//                continue;
//            }
//            JSONObject data = JSONObject.parseObject(body).getJSONObject("data");
//            String newOrderAmount = data.getString("newOrderAmount");
//            String logisticsAmount = data.getString("logisticsAmount");
//            orderExtend.setNewOrderAmount(newOrderAmount);
//            orderExtend.setLogisticsAmount(logisticsAmount);
//            erpSellerOrderExtendMapper.updateById(orderExtend);
//        }
//    }
//
//    @Override
//    public R<Object> getOrderList(String sellerId, String createDateStart, String createDateEnd) {
//        Map<String, Object> returnMap = new HashMap<>();
//        returnMap.put("sellerId", sellerId);
//        if (createDateStart == null) {
//            //开始时间为上次执行的最后时间+5分钟，该5分钟为定时任务间隔
//            String lastTime = configService.selectConfigByKey("ae.getOrder.lastTime");
////            String timeInterval = configService.selectConfigByKey("ae.getOrder.timeInterval");
//            //转为太平洋时间
//            String targetTime = TimeZoneTransition.transition(lastTime);
//            returnMap.put("createDateStart", DateUtil.offset(DateUtil.parse(targetTime), DateField.MINUTE, -Integer.valueOf(1)));
//            returnMap.put("createDateEnd", TimeZoneTransition.transition(DateUtil.now()));
//        } else {
//            returnMap.put("createDateStart", TimeZoneTransition.transition(createDateStart));
//            returnMap.put("createDateEnd", TimeZoneTransition.transition(createDateEnd));
//        }
//        returnMap.put("currentpage", "1");
//        returnMap.put("pageSize", 20);
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpOrder/getAEOrderList", returnMap, String.class);
//        String body = (String) forEntity.getBody();
//        log.info(JSONObject.parseObject(body).getString("msg"));
//
//        //Erp从AE获取订单
//        returnMap.put("sellerId", sellerId);
//        ErpSellerStoreEmpower empower = erpSellerStoreEmpowerMapper.selectById(sellerId);
//        returnMap.put("sellerOperatorLoginId", empower.getStoreUserName());
//        returnMap.put("beginTime", createDateStart);
//        returnMap.put("endTime", createDateEnd);
//        //将AE的收货人地址信息保存到Erp中
//
//        //Ae接口
//        forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpOrder/getAeOrderToERP", returnMap, String.class);
//        body = (String) forEntity.getBody();
//        //将获取的result进行解码
//        System.out.println(body);
//        if (body.equals("未查找到数据")) {
//            return R.ok("暂无新订单");
//        }
//        List<ErpSellerOrder> orderList = JSONArray.parseArray(body, ErpSellerOrder.class);
//        //for循环存入数据库
//        return iAeSaveOrderService.saveListInErp(orderList);
//    }
//
//
//    @Override
//    public R<Object> queryOrderFromAeByOrderId(Long storeId, Long orderId) {
//        Map<String, Object> map = new HashMap<>();
//        //1、获取单个订单，拉取到速卖通
//        map.put("storeId", storeId);
//        map.put("orderId", orderId);
//        ResponseEntity<String> forEntity = restTemplate
//                .postForEntity(aeConfig.getEndpoint() + "/erp/erpOrder/queryOrderFromAeByOrderId", map, String.class);
//        String body = (String) forEntity.getBody();
//        JSONObject bodyJson = JSONObject.parseObject(body);
//        List<ErpSellerOrder> orderList = JSONArray.parseArray(bodyJson.getString("data"), ErpSellerOrder.class);
//        //将返回的订单信息保存至对应表里去
//        System.out.println(orderList);
//        return iAeSaveOrderService.saveListInErp(orderList);
//    }
//
//    @Override
//    public void removeDuplicateOrders() {
//        //查询订单表中重复的数据
//        List<Long> orderIdList = erpSellerOrderMapper.queryDuplicateOrders();
//        if (orderIdList.size() > 1) {
//            //有重复数据
//            for (Long id : orderIdList) {
//                ErpSellerOrder order = erpSellerOrderMapper.selectOne(
//                        new LambdaQueryWrapper<ErpSellerOrder>()
//                                .eq(ErpSellerOrder::getOrderId, id)
//                                .orderByAsc(ErpSellerOrder::getCreateTime)
//                                .last("limit 1")
//                );
//                erpSellerOrderMapper.deleteById(order);
//            }
//        }
//        //查询地址表中重复的数据
//        List<Long> addressOrderList = erpSellerOrderMapper.queryDuplicateAddressOrders();
//        if (addressOrderList.size() > 1) {
//            //有重复数据
//            for (Long id : addressOrderList) {
//                ErpSellerOrder order = erpSellerOrderMapper.selectOne(
//                        new LambdaQueryWrapper<ErpSellerOrder>()
//                                .eq(ErpSellerOrder::getOrderId, id)
//                                .orderByAsc(ErpSellerOrder::getCreateTime)
//                                .last("limit 1")
//                );
//                erpSellerOrderMapper.deleteById(order);
//            }
//        }
//    }
//
//    @Override
//    public R<Object> deleteDuplicateOrderProduct() {
//        List<String> productList = erpSellerOrderProductMapper.queryDuplicateOrderProduct();
//        return null;
//    }


}

